package Pong;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client extends Thread {

	private String IP = "localhost";
	private TekenPaneel tekenpaneel;
	boolean spelen = false;
	boolean stoppen = false;

	public Client(String IP, TekenPaneel tekenpaneel) {
		this.IP = IP;
		this.tekenpaneel = tekenpaneel;
	}

	public void run() {
		tekenpaneel.start();
		Socket kkSocket = null;
		PrintWriter out = null;
		BufferedReader in = null;
		String host;

		try {
			host = IP;
			kkSocket = new Socket(host, 4444);
			out = new PrintWriter(kkSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
		} catch (UnknownHostException ie) {
			System.err.println("Don't know about host");
			System.exit(1);
		} catch (IOException oe) {
			System.err.println("Couldn't get I/O for the connection");
			System.exit(1);
		}

		String fromServer;
		int[] finalxpos = new int[4];

		try {
			while(!spelen){
				fromServer = in.readLine();
				if(fromServer.equals("start")){
					spelen = true;
				}
			}
			
			while (spelen) { 		//het verzenden en ontvangen van data
							 		//Verzenden: out.println(String);
							 		//Ontvangen: fromServer = in.readLine(); waarbij fromServer je ontvangen String is
				
				////////////////////Verzenden////////////////////
				
				if(!stoppen){
					out.println("" + tekenpaneel.getXpos());
				}
				
				if(stoppen){
					out.println("stop");
				}
				
				////////////////////Ontvangen////////////////////
				
				try{
				
				fromServer = in.readLine();
				
				if(fromServer.equals("stop")){
					spelen = false;
				}
				
				String[] test = fromServer.split(" ");
					
				switch(test[0]){
				case "1": 
					finalxpos[0] = Integer.parseInt(test[1]);
					finalxpos[1] = -Integer.parseInt(test[2]);
					tekenpaneel.setbalx(Integer.parseInt(test[3]));
					tekenpaneel.setbaly(Integer.parseInt(test[4]));
					break;
				case "2":
					finalxpos[0] = Integer.parseInt(test[2]);
					finalxpos[1] = -Integer.parseInt(test[1]);
					tekenpaneel.setbalx(-Integer.parseInt(test[3]));
					tekenpaneel.setbaly(-Integer.parseInt(test[4]));
					break;
				default:
					break;
				}
				
				tekenpaneel.setXpos(finalxpos);
				
				}catch (java.net.SocketException se){
					System.exit(-1);
				}catch (Exception e){}
				
			}

			out.close();
			in.close();
			kkSocket.close();
			
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	public void thstop(){
		stoppen = true;
	}

	public static void slaap(int mSec) {
		try {
			Thread.currentThread().sleep(mSec);
		} catch (InterruptedException e) {
		}
	}
}